﻿using System;
using System.Collections;
using System.Collections.Generic;
using CfgMusic;
using CMPart;
using com.m3sdk.common;
using CommSDK;
using CSUtils;
using DG.Tweening;
using G02.PlayerData;
using GlobalTripleJump;
using m3sdk;
using TripleJump;
using U3dGame;
using U3dGameUI;
using U3dUtils;
using UI00;
using UnityEngine;
using UnityEngine.UI;

namespace G02.TripleJump.UI {
    public class UI_Main : UIBase {
        const string _tag = "UI_Main";
        public static string prefabPath;

        protected override string _GetUIPrefabPath() {
            if (prefabPath != null) {
                return prefabPath;
            }
            return "TripleJump/UI/UI_Main/UI_Main.prefab";
        }

        public static Transform parent;
        protected override EUIType _uiType => EUIType.e04_main;

        protected override Transform _GetUIParent() {
            if (parent != null) {
                return parent;
            }
            return UIBase.uiLayer2_uiMain;
        }

        Text jumpMaxDistance, coldCoinNumber;
        Button setupButton, adsButton, hatButton, jumpMaxDistanceButton;
        public RectTransform startGameText;

        TJBottomCard jumpButton = new TJBottomCard();
        TJBottomCard jetpackButton = new TJBottomCard();
        TJBottomCard offlineRevenueButton = new TJBottomCard();
        InputField inputName;
        RectTransform setupBack;
        AudioSource audioSource;
        UISetup setup = new UISetup();

        protected override void _Init() {
            m_rootRt.gameObject.SetActive(true);
            coldCoinNumber = m_rootRt.GetControl<Text>("coldCoinNumber/number");
            jumpMaxDistance = m_rootRt.GetControl<Text>("jumpMaxDistance/distance");
            setupButton = m_rootRt.GetControl<Button>("setupButton");
            jumpMaxDistanceButton = m_rootRt.GetControl<Button>("jumpMaxDistance");
            adsButton = m_rootRt.GetControl<Button>("adsButton");
            hatButton = m_rootRt.GetControl<Button>("hatButton");
            setupBack = m_rootRt.GetControl<RectTransform>("setupBack");
            setupBack.localScale = new Vector3(1, 0.01f, 1);

            setupButton.onClick.AddListener(delegate() {
                //C_UIManage.GetInstance.uI_Setup.Open(setupButton.transform,true);
                if (setupBack.localScale.y > 0.2f) {
                    setupBack.DOScaleY(0.01f, 0.6f).SetEase(Ease.OutBack);
                    setup.Close();
                } else {
                    setupBack.DOScaleY(1, 0.6f).SetEase(Ease.OutBack);
                    setup.Open();
                }
            });
            jumpMaxDistanceButton.onClick.AddListener(delegate() {
                HitBall.UI.SuperSetting.UI_SuperSetting.S_ClickEvent();
            });
            hatButton.onClick.AddListener(delegate() {
                UI_NpcPreview.Open(true);
            });
            TripleJumpData playerData = TripleJumpData.curr;
            jumpButton._Init(m_rootRt.GetControl<RectTransform>("bottomButton/button00"), this, EButtonType.e00_jump);
            jetpackButton._Init(m_rootRt.GetControl<RectTransform>("bottomButton/button01"), this, EButtonType.e01_jetpack);
            offlineRevenueButton._Init(m_rootRt.GetControl<RectTransform>("bottomButton/button02"), this, EButtonType.e02_offlineRevenue);
            inputName = m_rootRt.GetControl<InputField>("inputNameBack/inputName");

            CEventManager.instance.Register(TripleJumpData.tag_playerMaxDistance, delegate {
                jumpMaxDistance.text = TripleJumpData.curr.maxDistance.ToNumberStr() + "m";
            });

            CPayData.goldcoin += 0;
            CEventManager.instance.Register(CPayUtils.tag_goldcoinChange, delegate {
                //})
                //C_PlayerData.curr.o_GoldCoinNumber.d_ChangleEvent += delegate(long number) {
                coldCoinNumber.text = "" + CPayData.goldcoin.currNum.ToNumberStr();
                CDelayMain.Delay(0.1f).SetPauseEnd("").onCallback = delegate {
                    if (isFlyEndAdsEvent) {
                        isFlyEndAdsEvent = false;
                        if (S_AdLogic_3C() == false) {
                            S_AdLogic_3B();
                        }
                    }
                };
            });
            TripleJumpData.curr.playerMaxDistance += 0;
            OfflineRevenueUtils.Init();

            adsButton.onClick.AddListener(delegate() {
                if (AdsSDK.IsCanShowInterstitialAd()) {
                    AdsSDK.ShowInterstitial(delegate(bool result) {
                        if (result == false) {
                            UI_Ads.GetInstance.Open(InterstitialAdLogicName, null);
                        }
                    });
                } else {
                    UI_Ads.GetInstance.Open(InterstitialAdLogicName, null);
                }
            });
            inputName.onValueChanged.AddListener(delegate(string ss) {
                ss = ss.Replace("#", "");
                Debug.LogFormat("设置玩家名称_______________{0}_____", ss);
                CBPlayerData1.curr.playerName = ss;
            });
            #if plus
            hatButton.gameObject.SetActive(true);
            inputName.gameObject.transform.parent.gameObject.SetActive(true);
            #else
            hatButton.gameObject.SetActive(false);
            inputName.gameObject.transform.parent.gameObject.SetActive(false);
            #endif

            setup.Init(m_rootRt.GetControl<RectTransform>("setupBack"), this);

            audioSource = m_rootRt.GetComponent<AudioSource>();
        }

        string InterstitialAdLogicName = "InterstitialAdButton";

        protected override void _Open(Dictionary<string, object> paraDic) {
        }

        public void GameStart() {
            Close();
            CGpCard.GetInstance().SetGiftVisibility(false);
            //CDelayMain.Delayed(0.1f).d_EndEvent = delegate () {
            //    effectImage.SetSiblingIndex(1000);
            //};
        }

        /// <summary>
        /// 飞行结束后金币变化出发的视频广告时间
        /// </summary>
        bool isFlyEndAdsEvent;

        public void GameReset() {
            isFlyEndAdsEvent = true;
            CGpCard.GetInstance().SetGiftVisibility(true);
            S_Logic_4();
        }

        /// <summary>
        /// 显示"滑动开始游戏"的文字提示
        /// </summary>
        IEnumerator IStartGameText() {
            if (TJGameData.gameState != EGameState.e01_GameReset) {
                startGameText.gameObject.SetActive(false);
                yield break;
            }
            startGameText.gameObject.SetActive(false);
            yield return new WaitForSeconds(0.3f);
            if (TJGameData.gameState != EGameState.e01_GameReset) {
                startGameText.gameObject.SetActive(false);
                yield break;
            }
            startGameText.gameObject.SetActive(true);
            yield return new WaitForSeconds(0.7f);
            mono.StartCoroutine(IStartGameText());
        }

        /// <summary>
        /// 设置音量
        /// </summary>
        public void SetMainMusicVolume(float volume) {
            audioSource.volume = volume;
        }

        /// <summary>
        /// 运营广告规则---3A.	当用户在升级某一项金币耗尽时；当前升级项有50%概率立即变为视频升级。
        /// </summary>
        void AdLogic_3A(TJBottomCard currentButton) {
            if (TJBottomCard._isShowAd != EButtonType.e55_null) {
                return;
            }
            if (UnityEngine.Random.value >= 0.5f) {
                currentButton.isShowRewardAd = true;
                currentButton._RefreshShow();
                Debug.LogFormat("视频升级.______________.S_AdLogic_3A");
            }
        }

        /// <summary>
        /// 运营广告规则---3B.	当用户飞行获得金币后，若金币¬数不够所有升级项升级时。3个升级项中随机1个升级项100%概率变为视频升级
        /// </summary>
        void S_AdLogic_3B() {
            if (TJBottomCard._isShowAd != EButtonType.e55_null) {
                return;
            }
            if (jumpButton.isCanBuy == false && jetpackButton.isCanBuy == false && offlineRevenueButton.isCanBuy == false) {
                //    if (C_BottomButton._isShowAd == E_ButtonType.e55_null) {
                // CDelayMain.Delayed(0).d_EndEvent = delegate () {
                Debug.LogFormat("视频升级.______________S_AdLogic_3B");
                float value = UnityEngine.Random.value;
                if (value <= 0.333f) {
                    jumpButton.isShowRewardAd = true;
                    jumpButton._RefreshShow();
                } else if (value <= 0.666f) {
                    jetpackButton.isShowRewardAd = true;
                    jetpackButton._RefreshShow();
                } else {
                    offlineRevenueButton.isShowRewardAd = true;
                    offlineRevenueButton._RefreshShow();
                }
                //  };
                // }
            }
        }

        /// <summary>
        /// 运营广告规则---3C.	若用户在5次飞行中，从未观看激励视频。则在第5次飞行后，无论金钱多少，
        /// 都将触发将“第一个升级项”强制变更为视频升级，直至用户观看后，才恢复可金钱升级。
        /// （当出现强制变更升级时，规则3.B无效）
        /// </summary>
        /// <returns></returns>
        bool S_AdLogic_3C() {
            if (TJBottomCard._isShowAd != EButtonType.e55_null) {
                return true;
            }
            if (TripleJumpData.curr.continueRewardAdNoPlayCount > 4) {
                TripleJumpData.curr.continueRewardAdNoPlayCount = 0;
                jumpButton.isShowRewardAd = true;
                jumpButton._RefreshShow();
                Debug.LogFormat("视频升级.______________.S_AdLogic_3C");
                return true;
            } else {
                return false;
            }
        }

        /// <summary>
        /// 运营规则---4.飞行结束后，20%概率弹出GPCard。（第1次结束后必弹，第2次后概率20%）
        /// </summary>
        void S_Logic_4() {
            if (TripleJumpData.curr.gameCount == 1) {
                CGpCard.GetInstance().OpenEvent();
            } else {
                if (UnityEngine.Random.value < 0.2f) {
                    CGpCard.GetInstance().OpenEvent();
                }
            }
        }

        public class TJBottomCard {
            Text level, number;
            RectTransform root, ads, mask, gradeImage, gradeAdImage;
            EButtonType type;
            UI_Main main;
            string rewardAdLogicName;

            public void _Init(RectTransform root, UI_Main main, EButtonType type) {
                this.root = root;
                this.main = main;
                this.type = type;
                level = root.GetControl<Text>("level");
                number = root.GetControl<Text>("number");
                ads = root.GetControl<RectTransform>("ads");
                mask = root.GetControl<RectTransform>("mask");
                gradeImage = root.GetControl<RectTransform>("gradeImage");
                gradeAdImage = root.GetControl<RectTransform>("gradeAdImage");
                rewardAdLogicName = "rewardAdLogic" + type;

                CEventManager.instance.Register(CPayUtils.tag_goldcoinChange, delegate {
                    //C_PlayerData.curr.o_GoldCoinNumber.d_ChangleEvent += delegate(long number) {
                    var number = CPayData.goldcoin.currNum;
                    if (isMaxLevel) {
                        mask.gameObject.SetActive(false);
                        gradeImage.gameObject.SetActive(false);
                        gradeAdImage.gameObject.SetActive(false);
                        CDelayMain.Delay(0).SetPauseEnd("").onCallback = delegate {
                            _RefreshShow();
                        };
                    } else {
                        needGoldCoin = long.MaxValue;
                        switch (type) {
                            case EButtonType.e00_jump:
                                // adLogicName = "e00_jump";
                                TripleJumpData.curr.levelData = TripleJumpData.curr.playerJumpLevel;
                                needGoldCoin = Cfg_PlayerProperty.Get(TripleJumpData.curr.levelData).JumpUpgradeNeedColdCoin;
                                break;
                            case EButtonType.e01_jetpack:
                                // adLogicName = "e01_jetpack";
                                TripleJumpData.curr.levelData = TripleJumpData.curr.playerJetpackLevel;
                                needGoldCoin = Cfg_PlayerProperty.Get(TripleJumpData.curr.levelData).JetpackUpgradeNeedColdCoin;
                                break;
                            case EButtonType.e02_offlineRevenue:
                                //adLogicName = "e02_offlineRevenue";
                                TripleJumpData.curr.levelData = TripleJumpData.curr.playerOfflineRevenueLevel;
                                needGoldCoin = Cfg_PlayerProperty.Get(TripleJumpData.curr.levelData).OfflineRevenueUpgradeNeedColdCoin;
                                break;
                        }
                        isCanBuy = number >= needGoldCoin ? true : false;
                        if (isCanBuy) {
                            Debug.LogFormat("按钮可以升级._____________.{0}", type);
                        }

                        if (false) {
                            //刷新免费广告
                            if (goldCoinRefreshFrame != Time.frameCount) {
                                _isShowAd = EButtonType.e55_null;
                            }
                            goldCoinRefreshFrame = Time.frameCount;
                            //免费广告
                            if (TripleJumpData.curr.gameCount > 1) {
                                if (isCanBuy == false && type != EButtonType.e02_offlineRevenue) {
                                    if (_isShowAd == EButtonType.e55_null) {
                                        float currentGameSystemTime = CGameSystemTime.GetInstance.CurrentGameSystemTime;
                                        if (currentGameSystemTime > TripleJumpData.curr.adsStartTime + 3600 * 4) {
                                            TripleJumpData.curr.adsStartTime = (int)currentGameSystemTime;
                                            TripleJumpData.curr.adsPlayCount = 0;
                                        }
                                        if (TripleJumpData.curr.adsPlayCount < 10) {
                                            if (UnityEngine.Random.value < 0.2f) {
                                                isShowRewardAd = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        CDelayMain.Delay(0).SetPauseEnd("").onCallback = delegate {
                            _RefreshShow();
                        };
                    }
                });
                root.GetComponent<Button>().
                    onClick.AddListener(delegate() {
                        if (isShowRewardAd) {
                            TripleJumpData.curr.adsPlayCount++;
                            if (AdsSDK.IsCanShowRewardAd()) {
                                AdsSDK.ShowRewardAds(S_Upgrade);
                            } else {
                                UI_Ads.GetInstance.Open(rewardAdLogicName, S_Upgrade);
                            }
                        } else {
                            if (isCanBuy) {
                                S_Upgrade(false);
                            } else {
                                // mask.gameObject.SetActive(false);
                            }
                        }
                    });
                CPayData.goldcoin += 0;
            }

            int goldCoinRefreshFrame;

            /// <summary>
            /// 升级属性
            /// </summary>
            void S_Upgrade(bool isAdReward) {
                if (isAdReward == false) {
                    if (isCanBuy == false) { //避免同时点击多个按钮
                        return;
                    }
                    CPayData.goldcoin -= needGoldCoin;
                } //else {
                //    C_PlayerData.GetInstance.o_GoldCoinNumber.Value += 0;
                // }
                TripleJumpData.curr.levelData++;

                if (isShowRewardAd) {
                    isShowRewardAd = false;
                } else {
                    if (isCanBuy == false) { //金币购买--当前相金币已不足
                        main.AdLogic_3A(this);
                    }
                }
                //数据统计分析
                if (CPara.onPlayerPropertyUpgrade != null) {
                    CPara.onPlayerPropertyUpgrade((int)type, TripleJumpData.curr.levelData, isAdReward);
                }
                CMusicManage.PlayMusic(MusicCfg.Upgrade);
                CDefEffectManage.PlayEffect(GlobalTripleJumpCfg.artPath_button_upgrade, root.position);
                //CDelayMain.Delayed(0).d_EndEvent = delegate () {
                _RefreshShow();
                //};

                root.localScale = Vector3.one;
                root.DOScale(Vector3.one * 0.8f, 0.15f).
                    OnComplete(delegate() {
                        root.DOScale(Vector3.one, 0.15f);
                    });
            }

            public bool isCanBuy;
            //LongData levelData;
            long needGoldCoin;
            bool isMaxLevel;

            public void _RefreshShow() {
                Cfg_PlayerProperty cfg = Cfg_PlayerProperty.Get(TripleJumpData.curr.levelData);
                if (cfg == null) {
                    isMaxLevel = true;
                } else {
                    isMaxLevel = false;
                }
                if (isMaxLevel) {
                    level.text = CL.G("o_max"); //C_UIManage.GetInstance.uILanguage.UI_Main.o_max;
                } else {
                    if (type != EButtonType.e02_offlineRevenue) {
                        level.text = "level " + TripleJumpData.curr.levelData;
                    } else {
                        int ii = (int)Cfg_PlayerProperty.Get(TripleJumpData.curr.levelData).OfflineRevenueValue;
                        level.text = $"${+ii} / min";
                    }
                }
                if (isMaxLevel) {
                    number.text = "0";
                } else {
                    if (isShowRewardAd) {
                        number.text = CL.G("o_free"); //C_UIManage.GetInstance.uILanguage.UI_Main.o_free);
                        ads.gameObject.SetActive(true);
                    } else {
                        number.text = needGoldCoin.ToNumberStr();
                        ads.gameObject.SetActive(false);
                    }
                }

                bool isShow = isCanBuy || isShowRewardAd;

                gradeAdImage.gameObject.SetActive(isShowRewardAd);
                gradeImage.gameObject.SetActive(isShow && !isShowRewardAd);

                mask.gameObject.SetActive(!isShow);

                root.SetUiLogoLight(isShow);
            }

            public bool isShowRewardAd {
                get { return type == _isShowAd ? true : false; }
                set {
                    if (value == true) {
                        _isShowAd = type;
                    } else {
                        _isShowAd = EButtonType.e55_null;
                    }
                }
            }
            public static EButtonType _isShowAd = EButtonType.e55_null;

            public class CPara {
                /// <summary>
                /// 类型，等级，是否奖励广告
                /// </summary>
                public static Action<int, int, bool> onPlayerPropertyUpgrade;
            }
        }
        public enum EButtonType { e00_jump = 0, e01_jetpack = 1, e02_offlineRevenue = 2, e55_null = 55, }

        class UISetup {
            RectTransform root;
            CToggle shakeBtn, musicBtn;

            public void Init(RectTransform root, UI_Main main) {
                this.root = root;
                shakeBtn = root.GetControl<CToggle>("vibrateToggle");
                musicBtn = root.GetControl<CToggle>("musicToggle");

                UI_LanguageSetting.languageDic = new Dictionary<int, string>() {
                    { 6, "中文简体(ChineseSimplified)" }, { 41, "中文繁体(ChineseTraditional)" }, { 10, "English(English)" }, //英语
                };

                shakeBtn.onSelectEvent += delegate(CToggle toggle) {
                    CMusicManage.PlayMusic(MusicCfg.button_negative);
                    TripleJumpData.curr.mobileVibrate = toggle.isSelected;
                    if (openFrame != Time.frameCount) {
                        if (toggle.isSelected) {
                            CVibrator.OpenVibrator(0, 400);
                        } else {
                            CDelayMain.Delay(0.4f).SetPauseEnd("").onCallback = delegate {
                                CVibrator.OpenVibrator(0, 400);
                            };
                        }
                    }
                    CVibrator.isUse = toggle.isSelected;
                };
                musicBtn.onSelectEvent += delegate(CToggle toggle) {
                    int value = toggle.isSelected ? 1 : 0;
                    TripleJumpData.curr.mobileMusic = toggle.isSelected;
                    if (toggle.isSelected) {
                        AudioListener.volume = value;
                    } else {
                        CDelayMain.Delay(0.4f).SetPauseEnd("").onCallback = delegate {
                            AudioListener.volume = value;
                        };
                    }
                    CMusicManage.PlayMusic(MusicCfg.button_negative);
                };
                AudioListener.volume = TripleJumpData.curr.mobileMusic ? 1 : 0;
                CVibrator.isUse = TripleJumpData.curr.mobileVibrate;
            }

            int openFrame;

            public void Open() {
                openFrame = Time.frameCount;
                //C_MonoMonitor.GetInstance.S_UpdateEventAdd(0, UI_SuperSetting.S_Update);
                CMusicManage.PlayMusic(MusicCfg.button_positive);
                shakeBtn.S_Select(TripleJumpData.curr.mobileVibrate);
                musicBtn.S_Select(TripleJumpData.curr.mobileMusic);
            }

            public void Close() {
                CMusicManage.PlayMusic(MusicCfg.button_negative);
                // base.Close();
                // C_MonoMonitor.GetInstance.S_UpdateEventRemove(UI_SuperSetting.S_Update);
            }
        }
    }
}
